package com.fingard.dsp.bank.directbank.cpcn01;

import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.Base64Helper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
/**
 *  中金渠道单笔代付
 *  	-- 当前支持银谷接入
 */
public class CPCN01SinglePay extends CPCN01Base implements ISinglePay {
	/**
	 * 单笔代付交易提交
	 */
	public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
		RetAtsSglDetail tmpRetDetail = d_190802(p_req1908);
		
		if(tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)){
			tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
		}
		
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	 }

	@Override
	public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
		return null;
	}

	//190802对外支付
	private RetAtsSglDetail d_190802(ReqSingle p_req1908) throws Exception{
		RetAtsSglDetail retDetail = new RetAtsSglDetail();
		
		ActSetItem actItem = getBankConfig().getActSetItem(p_req1908.singleDetail.recAct, "");
		if (actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)|| !FileHelper.existFile(actItem.oppCertFilePath)) {
			if (actItem == null) {
				throw new Exception("未找到账号" + p_req1908.singleDetail.recAct + "对应的商户配置节点");
			} else {
				throw new Exception("账号" + p_req1908.singleDetail.recAct + "对应的证书文件不存在");
			}
		}
		
		CPCN01Header bankHeader = new CPCN01Header();
		bankHeader.transCode = "4530";
		
		XmlTextWriter xmlWriter = new XmlTextWriter();
		//报文串需要整个字符串传送，中间需无回车符，否则会签名出错,适用于需要签名的原始串
		xmlWriter.autoFormat = false;
		writeCommonHeader(xmlWriter, bankHeader);
		
		xmlWriter.writeElementString("TxCode", bankHeader.transCode);
		xmlWriter.writeElementString("InstitutionID", actItem.merchantId);
		xmlWriter.writeEndElement();
		xmlWriter.writeStartElement("Body");
		xmlWriter.writeElementString("TxSN", p_req1908.singleDetail.askNumber);
		xmlWriter.writeStartElement("Payer");// 付款人
		xmlWriter.writeElementString("PaymentAccountName", p_req1908.singleDetail.payName);
		xmlWriter.writeElementString("PaymentAccountNumber", p_req1908.singleDetail.payAct);
		xmlWriter.writeEndElement();
		xmlWriter.writeStartElement("Payee");
		
		if (p_req1908.singleDetail.isPrivate.equals("1")) {
			xmlWriter.writeElementString("AccountType", "11");//个人账户
		}else {
			xmlWriter.writeElementString("AccountType", "12");//企业账户
		}
		
		xmlWriter.writeElementString("BankID", getBankConfig().getMapValueByKey("bankMapping", p_req1908.singleDetail.payBankCode));// 银行数字编码
		xmlWriter.writeElementString("BankAccountName", p_req1908.singleDetail.recName);
		xmlWriter.writeElementString("BankAccountNumber", p_req1908.singleDetail.recAct);
		xmlWriter.writeElementString("PhoneNumber", p_req1908.singleDetail.cellPhone);
		xmlWriter.writeEndElement();
		xmlWriter.writeElementString("Amount", StringHelper.amountMultiply100(p_req1908.singleDetail.payAmount));
		xmlWriter.writeElementString("Remark", p_req1908.singleDetail.memo);
		xmlWriter.writeEndElement();
		xmlWriter.writeEndDocument();
				
		// 发送银行
		String[] tmpStrRet = sendToBank("sync",xmlWriter.toXmlString(),actItem);
		
		// 解析银行返回
		if(tmpStrRet[0].length() == 0){
			String[] respInfo = tmpStrRet[1].split(",");
			String respXml = Base64Helper.getFromBase64(respInfo[0], getCharset());
			
			WriteBankLogLn("银行返回的报文为：" + respXml);
			
			StringBuilder tmpSbMsg = new StringBuilder();
			XmlTextReader tmpBkReader = loadBankRespXmlReader(respXml, tmpSbMsg);
			
			if(tmpBkReader != null){
				String tmpRespCode = tmpBkReader.getFirstText("/Response/Head/Code");
				
				if (tmpRespCode.equals("2000")) {
					retDetail.respCode = "0";
					retDetail.reqSeqID = tmpBkReader.getFirstText("/Response/Body/TxSN");
					retDetail.transState = tmpBkReader.getFirstText("/Response/Body/Status");
					if ("40".equals(retDetail.transState)) {
						retDetail.respInfo = tmpBkReader.getFirstText("/Response/Body/ResponseMessage");
					} else {
						retDetail.respInfo = tmpBkReader.getFirstText("/Response/Head/Message");
					}
					retDetail.payInfoCode = retDetail.transState + "+" + tmpBkReader.getFirstText("/Response/Body/ResponseCode");
				}else {
					retDetail.respCode = "-1";
					retDetail.respInfo = tmpBkReader.getFirstText("/Response/Head/Message");
				}
			}else{
				retDetail.respCode = "-1";
				retDetail.respInfo = tmpSbMsg.toString();
			}
		}else if(tmpStrRet[0].equals(ConnState.FAIL)){
			retDetail.respCode = "0";
			retDetail.respInfo = tmpStrRet[1];
			retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
			retDetail.transState = PaymentState.FAIL_Payment;
			retDetail.payInfoCode = tmpStrRet[0];
		}else{
			retDetail.respCode = "-1";
			retDetail.respInfo = tmpStrRet[1];
		}
		return retDetail;
	}

	/**
	 * 单笔代付交易状态查询
	 */
	public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
		RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
		
		try{
			ActSetItem actItem = getBankConfig().getActSetItem(p_req1944.recAct, "");
			if (actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)|| !FileHelper.existFile(actItem.oppCertFilePath)) {
				if (actItem == null) {
					throw new Exception("未找到账号" + p_req1944.recAct + "对应的商户配置节点");
				} else {
					throw new Exception("账号" + p_req1944.recAct + "对应的证书文件不存在");
				}
			}
		
			CPCN01Header bankHeader = new CPCN01Header();
			bankHeader.transCode = "4532";
			
			XmlTextWriter xmlWriter = new XmlTextWriter();
			xmlWriter.autoFormat = false;
			writeCommonHeader(xmlWriter, bankHeader);
			
			xmlWriter.writeElementString("TxCode", bankHeader.transCode);
			xmlWriter.writeElementString("InstitutionID", actItem.merchantId);
			xmlWriter.writeEndElement();
			xmlWriter.writeStartElement("Body");
			xmlWriter.writeElementString("TxSN", p_req1944.askNumber);
			xmlWriter.writeEndElement();
			xmlWriter.writeEndDocument();

			// 发送银行
			String[] tmpStrRet = sendToBank("sync",xmlWriter.toXmlString(),actItem);			
			
			// 解析银行返回
			if(tmpStrRet[0].length() == 0){
				String[] respInfo = tmpStrRet[1].split(",");
				String respXml = Base64Helper.getFromBase64(respInfo[0], getCharset());
				
				WriteBankLogLn("银行返回的报文为：" + respXml);
				
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(respXml, tmpSbMsg);
				
				if(tmpBkReader != null){
					String tmpRespCode = tmpBkReader.getFirstText("/Response/Head/Code");
					
					if (tmpRespCode.equals("2000")) {
						tmpRetAtsDetail.respCode = "0";
						tmpRetAtsDetail.respInfo = tmpBkReader.getFirstText("/Response/Head/Message");
						tmpRetAtsDetail.reqSeqID = tmpBkReader.getFirstText("/Response/Body/TxSN");
						tmpRetAtsDetail.transState = tmpBkReader.getFirstText("/Response/Body/Status");
						tmpRetAtsDetail.payInfoCode = tmpRetAtsDetail.transState;
					}else {
						tmpRetAtsDetail.respCode = "0";
						tmpRetAtsDetail.respInfo = tmpBkReader.getFirstText("/Response/Head/Message");
						tmpRetAtsDetail.transState = tmpRespCode;
						tmpRetAtsDetail.payInfoCode =tmpRespCode;
					}
				}else{
					tmpRetAtsDetail.respCode = "-1";
					tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
				}
			}else{
				tmpRetAtsDetail.respCode = "-1";
				tmpRetAtsDetail.respInfo = tmpStrRet[1];
			}
		}catch (Exception e) {
			tmpRetAtsDetail.respCode = "-1";
			tmpRetAtsDetail.respInfo = e.getMessage();
			e.printStackTrace();
		}
		
		retAts.writeRetDetail(tmpRetAtsDetail);
		return retAts;
	}

	@Override
	public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
		return null;
	}
}
